package com.apes.scm.stock.transfer.model;

import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.fileserver.File;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessType;
import com.apes.framework.plugin.soe.store.database.repository.BusinessTypeRepository;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.stock.transfer.repository.PickRepository;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.*;

/**
 * 功能：仓库作业（拣配、调拨）
 *
 * @author xul
 * @create 2018-01-26 9:26
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Pick.CONST_TABLE_NAME, indexes = {@Index(name = "i_stock_pick_origin", columnList = "origin")})
public class Pick extends Model {
    public static final String CONST_TABLE_NAME = "stock_pick";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "物流交货单", prefix = "JH%(company)%(yy)%(month)", padding = 5, useDateRange=true)
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "partner_id", referencedColumnName = "id")
    @Comment("业务伙伴")
    private PartyRole partner;

    @Column(name = "origin", length = 30)
    @Comment("来源单据号码")
    private String origin;

    @Column(name = "origin_business_type", length = 32, nullable = false)
    @Comment("源单据类型")
    private String originBusinessType;

    @Transient
    private String originBusinessTypeName;

    public String getOriginBusinessTypeName(){
        if (originBusinessType == null) return null;
        BusinessType businessType = SpringManager.getBean(BusinessTypeRepository.class).findOne(originBusinessType);
        if(businessType != null) return businessType.getName();
        return null;
    }

    @Column(name = "source", length = 30)
    @Comment("源单据号码")
    private String source; //源单据(例如：老框架生成新框架采购订单，采购订单入库，此时记录老框架的单号)

//    @Column(name = "source_business_type", length = 32)
//    private String sourceBusinessType; // 源单据类型
//
//    @Column(name = "origin_business_type_name", length = 64)
//    @Comment("来源单据类型名称")
//    private String originBusinessTypeName;

    @States(name = "订单状态", values = {
            @State(id = "confirmed", name = "确认"),
            @State(id = "done", name = "已完成"),
//            @State(id = "withdraw", name = "撤回"),
            @State(id = "locked", name = "扫码锁定"),
            @State(id = "cancel", name = "已取消")})
    @Column(name = "state", length = 10, nullable = false)
    @Comment("状态")
    private String state;

    public void setState(String state) {
        if ("done".equals(this.state) && !"withdraw".equals(state)) {
            throw new RuntimeException("交货单已完成，不允许变更！");
        }
        if ("cancel".equals(this.state)) {
            throw new RuntimeException("交货单已取消，不允许变更！");
        }
        this.state = state;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "move_type", referencedColumnName = "id")
    @Comment("交货方式")
    private Enumeration moveType; //交货方式：("direct", "部分交货"), ("one", "一次性交货");

    @States(name = "交货类型", values = {
            @State(id = "receipt", name = "收货"),
            @State(id = "deliver", name = "发货")})
    @Column(name = "operation", length = 10, nullable = false)
    @Comment("交货类型")
    private String operation; //交货类型：("receipt", "收货"), ("deliver", "发货");

    @OneToMany(mappedBy = "pick", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<PickItem> pickItems = new HashSet(); //拣配明细

    public Set<PickItem> getPickItems() {
        for (PickItem item : pickItems) {
            item.setPick(this);
        }
        return pickItems;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "date_order")
    @Comment("单据日期")
    private Date dateOrder;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "done_uid", referencedColumnName = "id")
    @Comment("完成人")
    private PartyRole doneUid;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "date_done")
    @Comment("完成日期")
    private Date dateDone;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "min_date")
    @Comment("计划日期")
    private Date minDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "backorder_id", referencedColumnName = "id")
    @Comment("欠单于")
    private Pick backorder;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id", nullable = false)
    @Comment("仓库")
    private Location location;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "receipt_location_id", referencedColumnName = "id")
    @Comment("对方仓库")
    private Location receiptLocation;

    @Column(name = "note", length = 120)
    @Comment("备注")
    private String note;

    @Column(name = "app_scan_person", length = 64)
    @Comment("扫码人")
    private String appScanPerson;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "app_scan_date")
    @Comment("扫码时间")
    private Date appScanDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "withdraw_uid", referencedColumnName = "id")
    @Comment("撤回人")
    private PartyRole withdrawUid;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "withdraw_data")
    @Comment("撤回时间")
    private Date withdrawData;

    @Column(name = "parcel_list_no", length = 120)
    @Comment("包裹单号")
    private String parcelListNo;

    @Column(name = "supplier_party_b", length = 120)
    @Comment("乙方供应商")
    private String supplierPartyB;

    @Column(name = "supplier_name_party_b", length = 120)
    @Comment("乙方供应商名称")
    private String supplierNamePartyB;

    @File
    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "sign_voucher", columnDefinition = "CLOB")
    @Comment("图片附件")
    private String signVoucher;

    @Column(name = "customer_expand_id")
    @Comment("会员扩展表")
    private String customerExpandId;

    @Transient
    private Map formatCustomerExpandId; // 查询赋能扩展信息 - 提供给界面使用

    public Map getFormatCustomerExpandId() {
        if (StringUtils.isEmpty(customerExpandId)) return formatCustomerExpandId = null;
        String carLicense = SpringManager.getBean(DomainService.class).invoke("fn.fnCustomerExpandService.accordIdFindCarLicense", MapUtil.mapper("id", customerExpandId));
        return formatCustomerExpandId = MapUtil.mapper("id", customerExpandId, "carLicense", carLicense);
    }


    @Transient
    private boolean withDrawButtonHide = false;

    public boolean getWithDrawButtonHide() {
        if (!this.getOriginBusinessType().equals("Transfer") && !this.getOriginBusinessType().equals("CrossCompanyTransferNew")) return true;
        List existsIncompletes = SpringManager.getBean(PickRepository.class).findAll("SELECT ID FROM STOCK_PICK WHERE SOURCE = '" + this.getId() + "' AND operation = 'receipt'");
        if (existsIncompletes.size() == 0) return false; // 异步请求生成交货
        existsIncompletes = SpringManager.getBean(PickRepository.class).findAll("SELECT ID FROM STOCK_PICK WHERE SOURCE = '" + this.getId() + "' AND STATE IN ('confirmed', 'locked')");
        if (existsIncompletes.size() == 0) return true;
        return false;
    }

    /**
     * 检测是否自动交货
     */
    @Comment("自动交货")
    @States(name = "自动交货", values = {
            @State(id = "true", name = "是"),
            @State(id = "false", name = "否")})
    @Column(name = "auto", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    private boolean auto = false;

    @Transient
    private String originBusinessName;

    public String getOriginBusinessName() {
        return getBusinessTypeName("originBusinessType");
    }

    @Transient
    private double printNumber = 0;//打印次数

    public void cancel() {
        if (state.equals("locked")) {
            throw new RuntimeException("交货单锁定中，不允许交货！");
        } else if (state.equals("cancel")) {
            throw new RuntimeException("交货单已取消，不允许重复取消！");
        } else if (state.equals("done")) {
            throw new RuntimeException("交货单已完成，不允许取消！");
        }
        this.setState("cancel");
        this.setDateDone(new Date());
    }

    /**
     * 交货
     */
    public void delivery() {
        if (state.equals("locked")) {
            throw new RuntimeException("交货单锁定中，不允许交货！");
        } else if (state.equals("cancel")) {
            throw new RuntimeException("交货单已取消，不允许交货！");
        } else if (state.equals("done")) {
            throw new RuntimeException("交货单已完成，不允许重复交货！");
        }
        this.setState("done");
        this.setDateDone(new Date());
    }


}
